package com.example.demo.support.multipart;

import org.apache.commons.lang3.StringUtils;

import java.util.LinkedHashMap;

public class MultipartData extends LinkedHashMap<String, Object> implements Cloneable {

    public MultipartData include(String key, Object val) {
        super.put(key, val);
        return this;
    }

    public <T> T includeAndReturn(String key, T val) {
        super.put(key, val);
        return val;
    }

    public Object get(String key) {
        return StringUtils.isNoneBlank(key) ? super.get(key) : null;
    }

    public <T> T getPart(String key, Class<T> target) {
        if (StringUtils.isNoneBlank(key)) {
            Object obj = get(key);

            if (null == obj) {
                return null;
            }

            if (obj.getClass().equals(target) || target.isAssignableFrom(obj.getClass())) {
                return (T) obj;
            } else {
                classCanNotCastException(obj.getClass(), target);
            }
        }
        return null;
    }

    public String getStringPart(String key) {
        String o = getPart(key, String.class);
        return null == o ? "" : o;
    }

    public Integer getIntegerPart(String key) {
        return getPart(key, Integer.class);
    }

    public Long getLongPart(String key) {
        return getPart(key, Long.class);
    }

    public Float getFloatPart(String key) {
        return getPart(key, Float.class);
    }

    public Double getDoublePart(String key) {
        return getPart(key, Double.class);
    }

    public Boolean getBooleanPart(String key) {
        return getPart(key, Boolean.class);
    }

    private void classCanNotCastException(Class<?> current, Class<?> target) {
        throw new ClassCastException(current.getName() + " can not cast to " + target.getName());
    }

    @Override
    public MultipartData clone() {
        return (MultipartData) super.clone();
    }
}
